package models

import (
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

// Proxy 代理信息表
type Proxy struct {
	ID            uuid.UUID `gorm:"type:char(36);primary_key"`
	CreatedAt     time.Time
	UpdatedAt     time.Time
	DeletedAt     gorm.DeletedAt `gorm:"index"`
	ExternalID    int            `gorm:"index"`                  // 外部系统的代理ID
	ProxyType     string         `gorm:"size:20;not null;index"` // http, socks5 等
	ProxyIP       string         `gorm:"size:100;not null;index"`
	ProxyPort     string         `gorm:"size:10;not null"`
	ProxyUser     string         `gorm:"size:100;index"`
	ProxyPassword string         `gorm:"size:100"`
	Note          string         `gorm:"size:255"`
	TagIDs        string         `gorm:"size:255"` // 标签ID，多个以空格分隔
	Active        bool           `gorm:"default:true;index"`
}

// ProxyApplication 代理应用历史表
type ProxyApplication struct {
	ID          uuid.UUID `gorm:"type:char(36);primary_key"`
	CreatedAt   time.Time
	UpdatedAt   time.Time
	DeletedAt   gorm.DeletedAt `gorm:"index"`
	ProxyID     uuid.UUID      `gorm:"type:char(36);index"` // 应用的代理ID
	UserID      uuid.UUID      `gorm:"type:char(36);index"` // 用户ID
	BrowserID   uuid.UUID      `gorm:"type:char(36);index"` // 浏览器ID
	BrowserName string         `gorm:"size:100"`            // 浏览器名称
	Success     bool           `gorm:"default:true"`        // 是否应用成功
	Message     string         `gorm:"size:255"`            // 应用结果消息
}

// BeforeCreate 创建前自动生成UUID
func (p *Proxy) BeforeCreate(tx *gorm.DB) (err error) {
	if p.ID == uuid.Nil {
		p.ID = uuid.New()
	}
	return
}

// BeforeCreate 创建前自动生成UUID
func (pa *ProxyApplication) BeforeCreate(tx *gorm.DB) (err error) {
	if pa.ID == uuid.Nil {
		pa.ID = uuid.New()
	}
	return
}

// 创建代理
func CreateProxy(proxy *Proxy) error {
	return DB.Create(proxy).Error
}

// 更新代理
func UpdateProxy(proxy *Proxy) error {
	return DB.Save(proxy).Error
}

// 根据ID获取代理
func GetProxyByID(id uuid.UUID) (*Proxy, error) {
	var proxy Proxy
	err := DB.First(&proxy, "id = ?", id).Error
	if err != nil {
		return nil, err
	}
	return &proxy, nil
}

// 根据外部ID获取代理
func GetProxyByExternalID(externalID int) (*Proxy, error) {
	var proxy Proxy
	err := DB.First(&proxy, "external_id = ?", externalID).Error
	if err != nil {
		return nil, err
	}
	return &proxy, nil
}

// 删除代理（物理删除）
func DeleteProxy(id uuid.UUID) error {
	return DB.Unscoped().Delete(&Proxy{}, "id = ?", id).Error
}

// ProxyListRequest 代理列表查询请求
type ProxyListRequest struct {
	Page      int    `json:"page" form:"page"`
	PageSize  int    `json:"pageSize" form:"pageSize"`
	ProxyIP   string `json:"proxyIP" form:"proxyIP"`
	ProxyUser string `json:"proxyUser" form:"proxyUser"`
	ProxyType string `json:"proxyType" form:"proxyType"`
}

// 获取代理列表（支持分页和筛选）
func GetProxyList(req *ProxyListRequest) ([]Proxy, int64, error) {
	var proxies []Proxy
	var total int64

	// 构建查询
	query := DB.Model(&Proxy{})

	// 添加筛选条件
	if req.ProxyIP != "" {
		query = query.Where("proxy_ip LIKE ?", "%"+req.ProxyIP+"%")
	}
	if req.ProxyUser != "" {
		query = query.Where("proxy_user LIKE ?", "%"+req.ProxyUser+"%")
	}
	if req.ProxyType != "" {
		query = query.Where("proxy_type = ?", req.ProxyType)
	}

	// 计算总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (req.Page - 1) * req.PageSize
	if err := query.Offset(offset).Limit(req.PageSize).Order("created_at DESC").Find(&proxies).Error; err != nil {
		return nil, 0, err
	}

	return proxies, total, nil
}

// 创建代理应用记录
func CreateProxyApplication(application *ProxyApplication) error {
	return DB.Create(application).Error
}

// 批量创建代理应用记录
func BatchCreateProxyApplications(applications []*ProxyApplication) error {
	return DB.Create(&applications).Error
}

// 根据用户ID和代理ID获取最近的应用记录
func GetProxyApplications(userID, proxyID uuid.UUID, limit int) ([]ProxyApplication, error) {
	var applications []ProxyApplication
	query := DB.Model(&ProxyApplication{})

	if userID != uuid.Nil {
		query = query.Where("user_id = ?", userID)
	}

	if proxyID != uuid.Nil {
		query = query.Where("proxy_id = ?", proxyID)
	}

	err := query.Order("created_at DESC").Limit(limit).Find(&applications).Error
	return applications, err
}

// 获取用户最近的代理应用记录
func GetUserProxyApplications(userID uuid.UUID, limit int) ([]ProxyApplication, error) {
	return GetProxyApplications(userID, uuid.Nil, limit)
}

// GetProxyApplicationsByProxyID 获取代理被应用的记录
func GetProxyApplicationsByProxyID(proxyID uuid.UUID, limit int) ([]ProxyApplication, error) {
	return GetProxyApplications(uuid.Nil, proxyID, limit)
}

// LastApplicationInfo 用于在浏览器列表中显示的简化应用信息
type LastApplicationInfo struct {
	AppliedAt time.Time `json:"appliedAt"`
	Success   bool      `json:"success"`
	Message   string    `json:"message"`
	ProxyID   uuid.UUID `json:"proxyId"` // 可以选择性加入，看前端是否需要
}

// 初始化表结构
func init() {
	// 在db.go的AutoMigrate中已经添加了这个表，这里不需要重复
}
